package com.fingard.crypto;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**AES加解密*/
public class AES {
	/**
     * AES加密，AES/CBC/PKCS5Padding
     * @param p_key 密钥
     * @param p_iv 向量
     * @param p_plainData 明文字节
     * @return 密文字节
     * @throws Exception
     */
	public static byte[] encryptCBC(byte[] p_key, byte[] p_iv, byte[] p_plainData) throws Exception {
        
        SecretKeySpec deskey = new SecretKeySpec(p_key, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec ivps = new IvParameterSpec(p_iv);
        cipher.init(Cipher.ENCRYPT_MODE, deskey, ivps);
        byte[] cipherBytes = cipher.doFinal(p_plainData);
        return cipherBytes;
    }
	
	/**
     * AES解密，AES/CBC/PKCS5Padding
     * @param p_key 密钥
     * @param p_iv 向量
     * @param p_cipherData 密文字节
     * @return 明文字节
     * @throws Exception
     */
    public static byte[] decryptCBC(byte[] p_key, byte[] p_iv, byte[] p_cipherData) throws Exception {
    	SecretKeySpec deskey = new SecretKeySpec(p_key, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec ivps = new IvParameterSpec(p_iv);
        cipher.init(Cipher.DECRYPT_MODE, deskey, ivps);
 
        byte[] plainBytes = cipher.doFinal(p_cipherData);
        return plainBytes;
    }
}
